from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes
from datetime import datetime, timedelta

# 1. 生成 RSA 私钥
private_key = rsa.generate_private_key(
    public_exponent=65537,  # 标准公钥指数
    key_size=2048           # 密钥长度
)

# 2. 将私钥保存为 PEM 文件
with open("private_key.der", "wb") as f:
    f.write(
        private_key.private_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption()  # 不加密私钥
            # 如需加密私钥，替换为：
            # encryption_algorithm=serialization.BestAvailableEncryption(b"mypassword")
        )
    )

# 3. 定义证书主题（Subject）
subject = x509.Name([
    x509.NameAttribute(NameOID.COUNTRY_NAME, "CN"),
    x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Beijing"),
    x509.NameAttribute(NameOID.LOCALITY_NAME, "Beijing"),
    x509.NameAttribute(NameOID.ORGANIZATION_NAME, "My Company"),
    x509.NameAttribute(NameOID.COMMON_NAME, "myapp.com"),
])

# 4. 设置证书有效期（当前时间到 365 天后）
valid_from = datetime.utcnow()
valid_to = valid_from + timedelta(days=365)

# 5. 构建自签名证书
certificate = (
    x509.CertificateBuilder()
    .subject_name(subject)
    .issuer_name(subject)  # 自签名证书，颁发者=主题
    .public_key(private_key.public_key())
    .serial_number(x509.random_serial_number())
    .not_valid_before(valid_from)
    .not_valid_after(valid_to)
    .add_extension(
        x509.BasicConstraints(ca=True, path_length=None),  # 标记为 CA 证书
        critical=True,
    )
    .sign(private_key, hashes.SHA256())  # 用私钥签名
)

# 6. 将证书保存为 PEM 文件
with open("certificate.der", "wb") as f:
    f.write(certificate.public_bytes(serialization.Encoding.DER))

print("私钥已保存到 private_key.der")
print("证书已保存到 certificate.der")